package cn.jtfadmin.base.lang.config;


import cn.jtfadmin.base.lang.common.domain.dto.ResultDTO;
import cn.jtfadmin.base.lang.common.utils.RequestUtils;
import cn.jtfadmin.base.lang.config.statuscode.ExceptionStatusDescribe;
import cn.jtfadmin.base.lang.config.statuscode.StatusCodeManager;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * webmvc 配置
 * 配置跨域, 配置日期转换, 配置异常处理, 配置 objectMapper
 *
 * @author jtf
 * @see #addCorsMappings(CorsRegistry)
 * @see #addFormatters(FormatterRegistry)
 * @see #configureHandlerExceptionResolvers(List)
 * @see #objectMapper(ObjectProvider)
 * @since 0.0.1
 */
@Configuration
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class WebConfig implements WebMvcConfigurer {


    private Logger logger = LoggerFactory.getLogger(WebConfig.class);


    /**
     * 日期格式表达式
     */
    private final String[] pattern;

    /**
     * 日期格式化呢
     */
    private final DateTimeFormatter[] dateTimeFormatterArray;

    @Autowired
    private StatusCodeManager statusCodeManager;


    public WebConfig() {
        pattern = new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", "yyyy-MM",
                "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH", "yyyy/MM",
                "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM.dd HH", "yyyy.MM",
                "yyyy年MM月dd日", "yyyy年MM月dd日 HH时mm分ss秒", "yyyy年MM月dd日 HH时mm分", "yyyy年MM月dd日 HH时", "yyyy年MM月",
                "yyyy", "HH:mm:ss", "HH:mm"};

        List<DateTimeFormatter> list = new ArrayList<>();
        list.add(DateTimeFormatter.ISO_DATE);
        list.add(DateTimeFormatter.ISO_TIME);
        list.add(DateTimeFormatter.ISO_LOCAL_DATE);
        list.add(DateTimeFormatter.ISO_LOCAL_TIME);
        list.add(DateTimeFormatter.BASIC_ISO_DATE);
        list.add(DateTimeFormatter.ISO_DATE_TIME);
        list.add(DateTimeFormatter.ISO_OFFSET_DATE);
        list.add(DateTimeFormatter.ISO_INSTANT);
        list.add(DateTimeFormatter.ISO_OFFSET_TIME);
        list.add(DateTimeFormatter.ISO_ORDINAL_DATE);
        list.add(DateTimeFormatter.ISO_WEEK_DATE);
        list.add(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        list.add(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        list.add(DateTimeFormatter.BASIC_ISO_DATE);
        list.add(DateTimeFormatter.RFC_1123_DATE_TIME);
        for (String s : pattern) {
            try {
                list.add(DateTimeFormatter.ofPattern(s));
            } catch (Exception ex) {
                // ignore
            }
        }
        dateTimeFormatterArray = list.toArray(new DateTimeFormatter[list.size()]);
    }


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, LocalDateTime.class, new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String s) {
                if (!StringUtils.hasText(s)) {
                    return null;
                }
                for (DateTimeFormatter dateTimeFormatter : dateTimeFormatterArray) {
                    try {
                        return LocalDateTime.parse(s, dateTimeFormatter);
                    } catch (Exception ex) {
                        // ignore
                    }
                }
                return null;
            }
        });

        registry.addConverter(String.class, LocalDate.class, new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String s) {
                if (!StringUtils.hasText(s)) {
                    return null;
                }
                for (DateTimeFormatter dateTimeFormatter : dateTimeFormatterArray) {
                    try {
                        return LocalDate.parse(s, dateTimeFormatter);
                    } catch (Exception ex) {
                        // ignore
                    }
                }
                return null;
            }
        });

        registry.addConverter(String.class, Date.class, new Converter<String, Date>() {
            @Override
            public Date convert(String s) {
                for (String p : pattern) {
                    try {
                        return new SimpleDateFormat(p).parse(s);
                    } catch (Exception ex) {
                        //
                    }
                }
                return null;
            }
        });

        registry.addConverter(String.class, LocalTime.class, new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert(String s) {
                for (String p : pattern) {
                    if (!StringUtils.hasText(s)) {
                        return null;
                    }
                    for (DateTimeFormatter dateTimeFormatter : dateTimeFormatterArray) {
                        try {
                            return LocalTime.parse(s, dateTimeFormatter);
                        } catch (Exception ex) {
                            // ignore
                        }
                    }
                    return null;
                }
                return null;
            }
        });

        registry.addConverter(LocalDateTime.class, String.class, new Converter<LocalDateTime, String>() {
            @Override
            public String convert(LocalDateTime s) {
                if (Objects.isNull(s)) {
                    return "";
                } else {
                    return s.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }
            }
        });
    }


    @Bean
    public ObjectMapper objectMapper(ObjectProvider<ObjectMapperConfig> objectMapperConfigs) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());

        if (Objects.nonNull(objectMapperConfigs)) {
            objectMapperConfigs.forEach(t -> t.doConfig(objectMapper));
        }
        return objectMapper;

    }

    /**
     * 配置跨域处理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*").
                allowedHeaders("*")
        ;
    }

    /**
     * 配置异常拦截
     */
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                logger.warn("url:{}, handler:{}", request.getRequestURL().toString(), handler, ex);
                String stackTrace = ExceptionUtils.getStackTrace(ex);
                String accept = request.getHeader("Accept");
                if (accept.indexOf("application/json") >= 0 || RequestUtils.isAjax(request)) {
                    ExceptionStatusDescribe statusDescribe = statusCodeManager.getExStatusDescribe(ex);
                    ResultDTO<String> resultDTO = ResultDTO.error(statusDescribe.getStatusCode(), statusDescribe.getDescribe(ex), stackTrace);
                    try {
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        ApplicationHolder.getApplicationContext().getBean(ObjectMapper.class)
                                .writeValue(response.getOutputStream(), resultDTO);
                    } catch (IOException e) {
                        // ignore
                    }

                } else {
                    try {
                        response.setContentType(MediaType.TEXT_HTML_VALUE);
                        ServletOutputStream outputStream = response.getOutputStream();
                        outputStream.write("<!DOCTYPE html>".getBytes());
                        outputStream.write("<html lang=\"zh-cmn-Hans\">".getBytes());
                        outputStream.write("<head>".getBytes());
                        outputStream.write(" <title>500</title>".getBytes());
                        outputStream.write("</head>".getBytes());
                        outputStream.write("<body>".getBytes());
                        outputStream.write(stackTrace.getBytes());
                        outputStream.write("</body>".getBytes());
                        outputStream.write("</html>".getBytes());
                    } catch (IOException e) {
                        // ignore
                    }
                }
                return null;
            }
        });
    }

}
